/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package GUI;

import Control.Control;
import DataBase.ServicioMenu;
import Logic.Clasificacion;
import Logic.Columna;
import Logic.Log;
import Logic.Tabla;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import javax.swing.BorderFactory;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.RowFilter;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

/**
 *
 * @author LiN
 */
public class GUI_Permisos extends javax.swing.JFrame {
    private TableRowSorter<TableModel> sorter;
    private Control control=Control.getInstance();
    private String SELECTED_TABLE;
    private GUI_ClasificationCataloge gui;
    ArrayList<Tabla> tablas;
    /**
     * Creates new form GUI_Permisos
     */
    public GUI_Permisos(GUI_ClasificationCataloge gui) {
        this.setTitle("Privileges Selection");
        this.gui=gui;
        initComponents();
        
        TitledBorder title1=BorderFactory.createTitledBorder("Table Selection");
        jPanel1.setBorder(title1);
        
        TitledBorder title2=BorderFactory.createTitledBorder("Column Selection");
        jPanel2.setBorder(title2);
        
        jTable1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        jTable2.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        sorter=new TableRowSorter<TableModel>(jTable1.getModel());
        jTable1.setRowSorter(sorter);
        
        tablas=new ArrayList(control.getSELECTED_CLASIFICACION().getTablaPermisos());
        //tablas=(ArrayList<Tabla>) control.getSELECTED_CLASIFICACION().getTablaPermisos().clone();
        
        loadTables();
        
        this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        setLocationRelativeTo(null);
        pack();
        setVisible(true);
        this.jTable1.getTableHeader().setReorderingAllowed(false);
        this.jTable2.getTableHeader().setReorderingAllowed(false);
    }
    
    public void clearTable(JTable jtable){
        while(jtable.getRowCount()>0){
            ((DefaultTableModel)jtable.getModel()).removeRow(0);
        }
    }
    
    public Tabla getTabla(String tabla){
        Iterator ite=tablas.iterator();
        Tabla aux=null;
        while(ite.hasNext()){
            aux=(Tabla) ite.next();
            if(aux.getNombre().equalsIgnoreCase(tabla))
                return aux;
        }
        return null;
    }
    
    public void loadTables(){
        ArrayList list;
        ServicioMenu sm=control.getServicioMenu();
        //list=(ArrayList) sm.listarTablas();
        list=(ArrayList) sm.allTables();
        
        Iterator ite=list.iterator();
        while(ite.hasNext()){
            String name=(String) ite.next();
            System.out.println(name);
            Clasificacion aux=control.getSELECTED_CLASIFICACION();

            Tabla tabla=aux.getTabla(name);
            if(tabla!=null){
                ((DefaultTableModel) jTable1.getModel()).addRow(new Object[]{name,tabla.isInsert(),tabla.isDelete(),tabla.isSelect()});
            }else{            
                ((DefaultTableModel) jTable1.getModel()).addRow(new Object[]{name,false,false,false});            
            }
            //ite.next();
        }
        //
        
    }
    
    public void loadColumn(){
        ArrayList list;
        ServicioMenu sm=control.getServicioMenu();      
        
     
        list=(ArrayList) sm.listarColumnas(SELECTED_TABLE);
      
        
        Iterator ite=list.iterator();
        while(ite.hasNext()){
            String name=(String) ite.next();
            //Clasificacion aux=control.getSELECTED_CLASIFICACION();
            Tabla tabla=getTabla(this.jLabel2.getText());
            if(tabla!=null){
                Columna col=tabla.getColumna(name);
                //System.out.println(name);
                
                if(col!=null){
                    //System.out.println(col.isInsert());
                    ((DefaultTableModel) jTable2.getModel()).addRow(new Object[]{name,col.isInsert(),col.isUpdate()});
                }else{
                    ((DefaultTableModel) jTable2.getModel()).addRow(new Object[]{name,false,false});
                }
            }else{            
                ((DefaultTableModel) jTable2.getModel()).addRow(new Object[]{name,false,false});            
            }
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTable2 = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jButton3 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Table Name", "Insert", "Delete", "Select"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Object.class, java.lang.Boolean.class, java.lang.Boolean.class, java.lang.Boolean.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                jTable1MouseReleased(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 539, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addGap(37, 37, 37)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 204, Short.MAX_VALUE)
                .addContainerGap())
        );

        jTable2.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Column Name", "Insert", "Update"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Object.class, java.lang.Boolean.class, java.lang.Boolean.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        jTable2.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                jTable2MouseReleased(evt);
            }
        });
        jScrollPane2.setViewportView(jTable2);

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jLabel1.setText("Table:");

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jLabel2.setText("Unknown");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel2)
                        .addGap(0, 425, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 207, Short.MAX_VALUE)
                .addContainerGap())
        );

        jButton3.setText("Save");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jButton2.setText("Cancel");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(jButton3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton2))
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton3)
                    .addComponent(jButton2))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        int val=JOptionPane.showConfirmDialog(null,"Are you sure?","Confirm",JOptionPane.YES_NO_OPTION);
        if(val==0){
            Clasificacion aux=control.getSELECTED_CLASIFICACION();
            aux.getTablaPermisos().clear();
            aux.setTablaPermisos(tablas);
            
            
            
            control.save_clasification();
            
            //Logs
            Log log = new Log(new Date(),control.getUser(),control.getSELECTED_SERVER(),Log.ASSIGN_PRIVILEGE,tablas.toString());
            control.insertLog(log);
            control.saveLogs();
            
            this.dispose();
            gui.loadTable2();
            
            JOptionPane.showMessageDialog(null,"Done...!!!");            
        }
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
       this.dispose();
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jTable1MouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseReleased
        if(jTable1.getSelectedRowCount()>0){
            boolean cambio=false;
            boolean insert=(boolean) ((DefaultTableModel)this.jTable1.getModel()).getValueAt(this.jTable1.getSelectedRow(),1);
            boolean delete=(boolean) ((DefaultTableModel)this.jTable1.getModel()).getValueAt(this.jTable1.getSelectedRow(),2);
            boolean select=(boolean) ((DefaultTableModel)this.jTable1.getModel()).getValueAt(this.jTable1.getSelectedRow(),3);

            this.setSELECTED_TABLE((String)((DefaultTableModel)this.jTable1.getModel()).getValueAt(this.jTable1.getSelectedRow(),0));
            this.jLabel2.setText(this.getSELECTED_TABLE());
            
            Tabla aux=getTabla(this.getSELECTED_TABLE());
            //System.out.println(this.getSELECTED_TABLE());
            if(insert || delete || select){
                if(aux==null){
                    aux=new Tabla();
                    aux.setNombre(this.getSELECTED_TABLE());
                    tablas.add(aux);
                }                
            }
            if(aux!=null){
                //System.out.println(aux.isInsert()+" "+insert);
                if(aux.isInsert()!=insert)
                    cambio=true;
                aux.setInsert(insert);
                aux.setDelete(delete);
                aux.setSelect(select);
            }

            clearTable(jTable2);
            loadColumn();
            
            for(int i=0;i<jTable2.getRowCount();i++){
                if(cambio){
                    ((DefaultTableModel)this.jTable2.getModel()).setValueAt(insert,i,1);    
                }
                if(aux!=null){
                    Columna col=aux.getColumna((String) ((DefaultTableModel)this.jTable2.getModel()).getValueAt(i,0));
                    if(col!=null){
                        //((DefaultTableModel)this.jTable2.getModel()).setValueAt(col.isUpdate(), i,2);
                        //System.out.println(col.isInsert()+" "+col.isUpdate());
                        if(!insert && !col.isUpdate()){
                            //System.out.println(col.getNombre());
                            aux.getColumans().remove(col);                            
                        }
                        if(cambio)
                            col.setInsert(insert);
                        
                    }else{
                        if(insert){ 
                            col=new Columna();
                            col.setNombre((String) ((DefaultTableModel)this.jTable2.getModel()).getValueAt(i,0));
                            col.setInsert(insert);
                            aux.getColumans().add(col);
                        }
                    }
                    if(aux.getColumans().size()==0 && !aux.isInsert() && !aux.isDelete() && !aux.isSelect()){
                        Tabla aux2=getTabla(this.getSELECTED_TABLE());
                        tablas.remove(aux2);
                    }
                }
            }
        }
    }//GEN-LAST:event_jTable1MouseReleased

    private void jTable2MouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable2MouseReleased
        if(jTable2.getSelectedRowCount()>0){
            boolean insert=(boolean) ((DefaultTableModel)this.jTable2.getModel()).getValueAt(this.jTable2.getSelectedRow(),1);
            boolean update=(boolean) ((DefaultTableModel)this.jTable2.getModel()).getValueAt(this.jTable2.getSelectedRow(),2);
            
            if(insert || update){
                Tabla aux=getTabla(this.getSELECTED_TABLE());
                if(aux==null){
                    aux=new Tabla();
                    aux.setNombre(this.getSELECTED_TABLE());          
                    tablas.add(aux);
                }
                Columna col=aux.getColumna((String) ((DefaultTableModel)this.jTable2.getModel()).getValueAt(this.jTable2.getSelectedRow(),0));
                if(col==null){
                    col=new Columna();
                    col.setNombre((String) ((DefaultTableModel)this.jTable2.getModel()).getValueAt(this.jTable2.getSelectedRow(),0));
                    aux.getColumans().add(col);                        
                }
                col.setInsert(insert);
                col.setUpdate(update);
            }
            
            if(!insert || !update){
                Tabla aux=getTabla(this.getSELECTED_TABLE());
                if(aux!=null){
                    Columna col=aux.getColumna((String) ((DefaultTableModel)this.jTable2.getModel()).getValueAt(this.jTable2.getSelectedRow(),0));
                    if(col!=null){
                        if(!insert && !update){
                            aux.getColumans().remove(col);
                            if(aux.getColumans().size()==0 && !aux.isInsert() && !aux.isDelete() && !aux.isSelect()){
                                Tabla aux2=getTabla(this.getSELECTED_TABLE());
                                tablas.remove(aux2);
                            }
                        }else{
                            col.setInsert(insert);
                            col.setUpdate(update);   
                        }
                    }
                }
            }
        }
    }//GEN-LAST:event_jTable2MouseReleased

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(GUI_Permisos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(GUI_Permisos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(GUI_Permisos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(GUI_Permisos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
               //new GUI_Permisos().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTable1;
    private javax.swing.JTable jTable2;
    // End of variables declaration//GEN-END:variables

    public String getSELECTED_TABLE() {
        return SELECTED_TABLE;
    }

    public void setSELECTED_TABLE(String SELECTED_TABLE) {
        this.SELECTED_TABLE = SELECTED_TABLE;
    }
}
